package com.dobby.demo.spring;

import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.data.redis.serializer.SerializationException;

import javax.sql.rowset.serial.SerialException;
import java.io.IOException;
import java.nio.charset.Charset;

/**
 * 使用jackson自定义的json序列化工具
 * Created by liguoqing on 2016/2/29.
 */
public class JsonRedisSerializer {

    private static final String EMPTY_JSON = "{}";

    private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");

    private ObjectMapper objectMapper = new ObjectMapper();

    public JsonRedisSerializer() {
    }

    /**
     * 序列化对象
     * @param obj
     * @return
     */
    public String serializeAsString(Object obj) {
        if(null == obj) {
            return EMPTY_JSON;
        }
        try {
            return this.objectMapper.writeValueAsString(obj);
        } catch (IOException ex) {
            throw new SerializationException("could not write JSON : " + ex.getMessage(), ex);
        }
    }

    /**
     * 反序列化
     * @param str
     * @param <T>
     * @return
     */
    public <T> T deserializeAsObject(String str, Class<T> clazz) {
        if(null == str || null == clazz) {
            return null;
        }
        try {
            return this.objectMapper.readValue(str, clazz);
        } catch (IOException ex) {
            throw new SerializationException("could not read VALUE :" + ex.getMessage(), ex);
        }
    }
}

